﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.IO;
using System.Text;
using Excel;

namespace OrderAggregator.InputFormats.KapitalAlfa
{
	/// <summary>
    /// ООО "Капитал "
    /// Альфа Ритейл Компани ООО
	/// </summary>
    public class KapitalAlfaFormat : Excel.BaseExcelFormat
	{

        public readonly static KapitalAlfaFormat Instance = new KapitalAlfaFormat();

        private KapitalAlfaFormat()
        {
        }

		/// <summary>
		/// Parse
		/// </summary>
		/// <param name="filePath"></param>
		/// <param name="getStream"></param>
		/// <returns></returns>
		public override BaseOrder Parse(string filePath, Func<System.IO.Stream> getStream)
		{
            if (!string.Equals(System.IO.Path.GetExtension(filePath), dotXLS, StringComparison.InvariantCultureIgnoreCase))
            {
                return null;
            }
           
            DataTable table;
            try
            {
                table = ReadAsDataTable(Path.GetFullPath(filePath));
            }
            catch
            {
                return null;
            }


            string number, client;
            DateTime date;
            if (!TryParseNumberAndDateAndClient(table, out number, out date, out client))
            {
                return null;
            }


			var order = new BaseOrder();
            order.Id = number;
            order.ReceiveTime = date;
            order.Client = client;

            var orderRows = GetOrderRows(table);

            foreach (var orderDataRow in orderRows)
            {
                var orderRow = new BaseOrderRow();
                orderRow.ProductCode = orderDataRow[0].ToString();
                orderRow.ProductName = orderDataRow[1].ToString();
                orderRow.UnitName = orderDataRow[3].ToString();
                orderRow.Count = decimal.Parse(orderDataRow[4].ToString(), BaseOrderFormat.RuCulture);                

                order.OrderRows.Add(orderRow);
            }
			return order;                     
        }
       

        private bool TryParseNumberAndDateAndClient(DataTable table, out string number, out DateTime date, out string client)
        {
            number = string.Empty;            
            date = DateTime.MinValue;
            client = string.Empty;

            var header = string.Empty;                                    
            var countField = 0;




            for (var i = 0; i < table.Rows.Count && countField < 3; i++)
            {
                var row = table.Rows[i];

                header = row[0] as string;

                var colmn2 = row[2].ToString();

                if (!string.IsNullOrEmpty(header))
                {

                    if (header.Contains("Заявка"))
                    {
                        var index1 = colmn2.IndexOf("№");
                        var index2 = colmn2.IndexOf("от");

                        if (index1 < 0 || index2 < 0)
                        {
                            return false;
                        }                              
                        index1 += "№".Length;                        
                        number = colmn2.Substring(index1, index2 - index1).Trim();
                        countField++;

                        index2 += "от".Length;
                        colmn2 = colmn2.Substring(index2, colmn2.Length-index2).Trim();
                        if (!string.IsNullOrEmpty(colmn2) && DateTime.TryParse(colmn2, out date))
                        {
                            countField++;                           
                        }
                    }
                    else
                    {
                        if (header.Contains("От кого"))
                        {
                            client = colmn2.Trim();
                            countField++;
                        }                        
                    }
                }
            }

            if (countField < 3)
            {
                return false;
            }
          
            return true;
        }

        private static List<DataRow> GetOrderRows(DataTable table)
        {
            var rows = new List<DataRow>();

            int startRow = -1;

            for (int i = 3; i < table.Rows.Count; i++)
            {
                var row = table.Rows[i];

                var strColmn1 = row[0] as string;
                var strColmn2 = row[1] as string;

                if (string.Equals(strColmn1, "Код", StringComparison.InvariantCultureIgnoreCase) &&
                    string.Equals(strColmn2, "Наименование", StringComparison.InvariantCultureIgnoreCase))
                {
                    startRow = i + 1;
                    break;
                }
            }

            if (startRow < 0)
            {
                return rows;
            }

            for (int i = startRow; i < table.Rows.Count; i++)
            {
                var row = table.Rows[i];

                var strColmn1 = row[0] as string;

                if (string.IsNullOrEmpty(strColmn1))
                {
                    break;
                }

                rows.Add(row);
            }

            return rows;
        }

	}
}
